import argparse, json, os
from multiprocessing import Pool
from sys import argv


def deobfs_task(x):
    _, old_path, entry = x
    print(f"{entry['path']} -> {old_path}")
    os.makedirs(os.path.dirname(old_path), exist_ok=True)
    os.rename(entry["path"], old_path)
    try:
        os.utime(old_path, (entry["attrs"]["atime"], entry["attrs"]["mtime"]))
        os.utime(old_path, ns=(entry["attrs"]["atime_ns"], entry["attrs"]["mtime_ns"]))
    except Exception as e:
        print(e)
    return old_path


def deobfs(directory: str, catalog: dict):
    with Pool() as pool:
        pool.map(
            deobfs_task,
            [(directory, old_path, entry) for old_path, entry in catalog.items()],
        )


if __name__ == "__main__":
    with open(argv[1] + ".catalog", "r") as file:
        catalog = json.load(file)

    os.makedirs(argv[1], exist_ok=True)
    with open(argv[1] + ".megafile", "rb") as mf:
        for _, entry in catalog.items():
            with open(entry["path"], "wb") as file:
                file.write(mf.read(entry["attrs"]["size"]))

    deobfs(argv[1], catalog)
